﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Services;
using PriceAlertService.Common;
using PriceAlertService.DataContract;

namespace PriceAlertService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        readonly chsboqgl_PriceAlertEntities _priceAlertEntities = new chsboqgl_PriceAlertEntities();
        [WebMethod]
        public string HelloWorld()
        {
            if (GetStockInfo.GetMatchPrice("ASM") == -1)
            {

            }
            return "Hello World";
        }
        public UsersData GetUserInfo(string phoneNumber)
        {
            var usersData = new UsersData();
            try
            {
                var user = _priceAlertEntities.Users.FirstOrDefault(p => p.PhoneNumber == phoneNumber);
                if (user != null)
                {
                    usersData.UserType = (Common.CommonEnum.UserType)user.UserType;
                    usersData.ExpirationDate = user.ExpirationDate;
                    return usersData;
                }
            }
            catch (Exception)
            {
                
            }
            return usersData;
        }

        [WebMethod]
        public bool ActiveAccount(string phoneNumber,string activeCode)
        {
            try
            {
                var user = _priceAlertEntities.Users.FirstOrDefault(u => u.PhoneNumber == phoneNumber);
                if (user != null && user.ActiveCode == activeCode)
                {
                    user.Actived = true;
                    _priceAlertEntities.SaveChanges();
                    return true;    
                }
                else
                {
                    return false;
                }
                
                
            }
            catch (Exception e)
            {
                return false;
            }
        }

        [WebMethod]
        public CommonEnum.RetCode Login(string phoneNumber)
        {
            try
            {
                var random = new Random();
                var activeCode = random.Next(1000, 9999);
                var userInDb = _priceAlertEntities.Users.FirstOrDefault(u => u.PhoneNumber == phoneNumber);
                //if user was created
                if (userInDb != null)
                {
                    if (userInDb.Banned)
                    {
                        return CommonEnum.RetCode.Banned;
                    }
                    //if user actived
                    if (userInDb.Actived == true)
                    {
                        if (userInDb.ExpirationDate < DateTime.Now)
                        {
                            return CommonEnum.RetCode.Expired;
                        }
                        else
                        {
                            return CommonEnum.RetCode.Success;
                        }
                    }
                    else
                    {
                        //send active code in sms
                        return CommonEnum.RetCode.NotActived;
                    }
                }
                else
                {
                    var user = new User
                    {
                        PhoneNumber = phoneNumber,
                        ActiveCode = activeCode.ToString(CultureInfo.InvariantCulture),
                        UserType = (int)CommonEnum.UserType.Trial,
                        ExpirationDate = DateTime.Now.AddDays(30)
                    };
                    _priceAlertEntities.Users.Add(user);
                    _priceAlertEntities.SaveChanges();
                    //send active code in sms
                    return CommonEnum.RetCode.CreateUserSuccess;
                }
            }
            catch (Exception e)
            {
                return CommonEnum.RetCode.SystemError;
            }
            
        }

        [WebMethod]
        public List<AlertDetailsData> SendRequest(string phoneNumber)
        {
            var resultDataList = new List<AlertDetailsData>();
            try
            {
                var priceAlertInDatas = _priceAlertEntities.PriceAlerts.Where(p => p.PhoneNumber == phoneNumber);
                foreach (var priceAlertInData in priceAlertInDatas)
                {
                    try
                    {
                        var alertDetails = new AlertDetailsData();
                        var currentPriceMatch = GetStockInfo.GetMatchPrice(priceAlertInData.StockSymbol);
                        if (currentPriceMatch > priceAlertInData.Ceiling && priceAlertInData.Ceiling != null && priceAlertInData.Ceiling > 0)
                        {
                            alertDetails.isAbove = true;
                            alertDetails.PriceAlertData = new PriceAlertData
                            {
                                Ceiling = (float)priceAlertInData.Ceiling,
                                StockSymbol = priceAlertInData.StockSymbol
                            };

                            priceAlertInData.Ceiling = 0;
                            _priceAlertEntities.SaveChanges();
                        }
                        if (currentPriceMatch < priceAlertInData.Floor && priceAlertInData.Floor != null && priceAlertInData.Floor > 0)
                        {
                            alertDetails.isAbove = false;
                            alertDetails.PriceAlertData = new PriceAlertData
                            {
                                Floor = (float)priceAlertInData.Floor,
                                StockSymbol = priceAlertInData.StockSymbol
                            };
                            priceAlertInData.Floor = 0;

                            resultDataList.Add(alertDetails);
                            _priceAlertEntities.SaveChanges();
                        }
                    }
                    catch (Exception e)
                    {
                        //send email
                    }
                }
            }
            catch (Exception e)
            {
                
            }
            return resultDataList;
        }

        [WebMethod]
        public bool UpdatePriceAlert(string phoneNumber, List<PriceAlertData> priceAlertDataRevs)
        {
            try
            {
                foreach (var priceAlertDataRev in priceAlertDataRevs)
                {
                    var priceAlertInData = _priceAlertEntities.PriceAlerts.FirstOrDefault(p => p.StockSymbol == priceAlertDataRev.StockSymbol && p.PhoneNumber == phoneNumber);
                    if (priceAlertInData == null)
                    {
                        //if not existed, insert
                        var priceAlert = new PriceAlert
                                       {
                                           PhoneNumber = phoneNumber,
                                           StockSymbol = priceAlertDataRev.StockSymbol,
                                           Ceiling = priceAlertDataRev.Ceiling,
                                           Floor = priceAlertDataRev.Floor
                                       };
                        _priceAlertEntities.PriceAlerts.Add(priceAlert);
                    }
                    else
                    {
                        //if existed,update
                        priceAlertInData.Ceiling = priceAlertDataRev.Ceiling;
                        priceAlertInData.Floor = priceAlertDataRev.Floor;
                        _priceAlertEntities.SaveChanges();
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}